package com.block.sms.service.send;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.block.common.service.LogFactory;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsReportInfo;
import com.block.db.entity.SmsTemplateInfo;
import com.block.db.mapper.SmsReportInfoMapper;
import com.block.sms.dto.*;
import com.block.sms.service.ISmsSendService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FeiXinYunSmsSendServiceImpl implements ISmsSendService {


    @Autowired
    private SmsReportInfoMapper smsReportInfoMapper;

    private static final Logger log = LogFactory.getCommLog();


    /**
     * 联通金融会销
     * 协议类型：http
     * 余额查询地址：http://api.feixinyun.com:9090/sms/balance/v1?appkey=3LhrTi
     * appkey：3LhrTi
     * appsecret：nDUr6W
     * appcode：1000
     * 客户端地址：https://console.feixinyun.com/sms-cloud
     * 登录账号：3LhrTi
     * 登录密码：EmgQaA
     * <p>
     * <p>
     * 移动金融会销
     * 协议类型：http
     * 余额查询地址：http://api.feixinyun.com:9090/sms/balance/v1?appkey=bxqENj
     * appkey：bxqENj
     * appsecret：euGWhU
     * appcode：1000
     * 客户端地址：https://console.feixinyun.com/sms-cloud
     * 登录账号：bxqENj
     * 登录密码：SjBPMn
     *
     * 电信金融会销
     * 协议类型：http
     * 余额查询地址：http://api.feixinyun.com:9090/sms/balance/v1?appkey=apEmL6
     * appkey：apEmL6
     * appsecret：DbbGqn
     * appcode：1000
     * 客户端地址：https://console.feixinyun.com/sms-cloud
     * 登录账号：apEmL6
     * 登录密码：YVL92x
     *
     * @param smsParamDTO
     * @param smsTemplate
     * @param smsConfigInfo
     * @return
     */
    @Override
    public SmsResultDTO sendSms(SmsParamDTO smsParamDTO, SmsTemplateInfo smsTemplate, SmsConfigInfo smsConfigInfo) {
        SmsResultDTO smsResultDTO = new SmsResultDTO();

        String appKey = smsConfigInfo.getAccountKey();
        String appSecret = smsConfigInfo.getAccountSecret();
        String appCode = "1000";

        String mobile = smsParamDTO.getMobie();

        // 只处理单个手机号，不再支持批量发送
        String cleanPhone = mobile.trim();
        StringBuilder resultDetails = new StringBuilder();

        // 验证手机号格式
        if (cleanPhone.length() < 3) {
            smsResultDTO.setSuccess(false);
            smsResultDTO.setCode("99999");
            smsResultDTO.setMessage("手机号格式错误: " + cleanPhone);
            return smsResultDTO;
        }

        try {
            // 获取当前时间戳（精确到毫秒）
            String timestamp = String.valueOf(System.currentTimeMillis());

            // 格式化短信内容
            JSONArray paramArr = smsParamDTO.getParamArray();
            String content = StrUtil.format(smsTemplate.getTemplateContent(), paramArr.stream().toArray());

            // 构建签名 (appkey+appsecret+timestamp)
            String sign = SecureUtil.md5(appKey + appSecret + timestamp).toLowerCase();

            // 构建请求参数
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("appkey", appKey);
            paramMap.put("appcode", appCode);
            paramMap.put("sign", sign);
            paramMap.put("timestamp", timestamp);
            paramMap.put("phone", cleanPhone);
            paramMap.put("msg", content);

            // 可选参数
            if (StrUtil.isNotBlank(smsParamDTO.getUid())) {
                paramMap.put("uid", smsParamDTO.getUid());
            }
            if (StrUtil.isNotBlank(smsParamDTO.getExtend())) {
                paramMap.put("extend", smsParamDTO.getExtend());
            }

            // 发送请求
            String bodyResult = HttpRequest.post(smsConfigInfo.getSendUrl())
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute()
                    .body();

            // 日志打印
            log.info("【飞信云短信服务】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getSendUrl(), JSONUtil.toJsonStr(paramMap), bodyResult);

            // 解析响应结果
            JSONObject resultJson = JSON.parseObject(bodyResult);
            String code = resultJson.getString("code");
            String desc = resultJson.getString("desc");

            resultDetails.append("手机号: ").append(cleanPhone).append(", 状态码: ").append(code).append(", 描述: ").append(desc);

            if ("00000".equals(code)) {
                // 检查具体手机号的发送状态
                JSONArray resultArray = resultJson.getJSONArray("result");
                if (resultArray != null && resultArray.size() > 0) {
                    JSONObject resultObj = resultArray.getJSONObject(0);
                    String status = resultObj.getString("status");

                    if ("00000".equals(status)) {
                        smsResultDTO.setSuccess(true);
                        smsResultDTO.setOutOrderNo(cleanPhone);
                        smsResultDTO.setCode("00000");
                        smsResultDTO.setMessage(resultDetails.toString());
                        smsResultDTO.setResult("发送成功");
                    } else {
                        smsResultDTO.setSuccess(false);
                        smsResultDTO.setCode("99999");
                        smsResultDTO.setMessage(resultDetails.toString());
                        smsResultDTO.setResult("发送失败");
                    }
                } else {
                    smsResultDTO.setSuccess(true);
                    smsResultDTO.setOutOrderNo(cleanPhone);
                    smsResultDTO.setCode("00000");
                    smsResultDTO.setMessage(resultDetails.toString());
                    smsResultDTO.setResult("发送成功");
                }
            } else {
                smsResultDTO.setSuccess(false);
                smsResultDTO.setCode("99999");
                smsResultDTO.setMessage(resultDetails.toString());
                smsResultDTO.setResult("发送失败");
            }
        } catch (Exception e) {
            log.error("发送短信异常 - 手机号: {}", cleanPhone, e);
            smsResultDTO.setSuccess(false);
            smsResultDTO.setCode("99999");
            smsResultDTO.setMessage("手机号: " + cleanPhone + ", 异常: " + e.getMessage());
            smsResultDTO.setResult("发送异常");
        }

        return smsResultDTO;
    }



    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

    @Override
    public QueryResultDTO querySendResult(QueryParamDTO queryParamDTO, SmsConfigInfo smsConfigInfo) {
        QueryResultDTO resultDTO = new QueryResultDTO();

        try {
            String appKey = smsConfigInfo.getAccountKey();
            String appSecret = smsConfigInfo.getAccountSecret();
            String appCode = "1000";

            String timestamp = String.valueOf(System.currentTimeMillis());

            String sign = SecureUtil.md5(appKey + appSecret + timestamp).toLowerCase();

            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("appkey", appKey);
            paramMap.put("appcode", appCode);
            paramMap.put("sign", sign);
            paramMap.put("timestamp", timestamp);


            String queryUrl = "http://api.feixinyun.com:9090/sms/report/v1";
            String response = HttpRequest.post(queryUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute()
                    .body();

            log.info("【飞信云短信服务】状态查询【url】{}【paramMap】{}【response】{}",
                    queryUrl, JSONUtil.toJsonStr(paramMap), response);

            JSONArray resultArray = JSON.parseArray(response);

            if (resultArray != null && resultArray.size() > 0) {
                // 过滤desc为超频和网咯波动的数据
                List<JSONObject> filteredResults = new ArrayList<>();
                for (int i = 0; i < resultArray.size(); i++) {
                    JSONObject item = resultArray.getJSONObject(i);
                    String desc = item.getString("desc");
                    if ("zx:0056".equals(desc) || "zx:0066".equals(desc) || "zx:1052".equals(desc) || "-22".equals(desc)) {
                        filteredResults.add(item);
                    }
                }

                // 保存查询结果到数据库
                saveReportInfoToDatabase(filteredResults);

                if (!filteredResults.isEmpty()) {
                    resultDTO.setSuccess(true);
                    resultDTO.setCode("00000");
                    resultDTO.setMessage("查询成功，找到" + filteredResults.size() + "条zx:0056状态的记录");
                    // 将过滤后的结果设置到result字段中
                    resultDTO.setResult(JSON.toJSONString(filteredResults));
                } else {
                    resultDTO.setSuccess(true);
                    resultDTO.setCode("00000");
                    resultDTO.setMessage("查询成功，但未找到desc为zx:0056的记录");
                }
            } else {
                resultDTO.setSuccess(true);
                resultDTO.setCode("00000");
                resultDTO.setMessage("查询成功，无结果数据");
            }
        } catch (Exception e) {
            log.error("查询短信状态异常", e);
            resultDTO.setSuccess(false);
            resultDTO.setCode("99999");
            resultDTO.setMessage("查询异常: " + e.getMessage());
        }

        return resultDTO;
    }
    /**
     * 保存短信报告信息到数据库
     * @param reportDataList 报告数据列表
     */
    /**
     * 保存短信报告信息到数据库
     * @param reportDataList 报告数据列表
     */
    private void saveReportInfoToDatabase(List<JSONObject> reportDataList) {
        try {
            if (reportDataList == null || reportDataList.isEmpty()) {
                return;
            }

            // 提取手机号列表
            List<String> mobiles = new ArrayList<>();
            List<SmsReportInfo> reportInfoList = new ArrayList<>();

            for (JSONObject item : reportDataList) {
                String mobile = item.getString("phone");
                mobiles.add(mobile);

                SmsReportInfo reportInfo = new SmsReportInfo();
                reportInfo.setMobile(mobile);
                reportInfo.setStatus(0);
                reportInfo.setDescText(item.getString("desc"));
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String reportTime = item.getString("report_time");
                LocalDateTime dateTime = LocalDateTime.parse(reportTime, formatter);
                reportInfo.setReportTime(dateTime);
                reportInfoList.add(reportInfo);
            }

            // 查询数据库中已存在且status为1的手机号记录
            List<SmsReportInfo> existingRecords = smsReportInfoMapper.selectList(
                    new QueryWrapper<SmsReportInfo>()
                            .in("mobile", mobiles)
                            .eq("status", 1)
            );

            if (!existingRecords.isEmpty()) {
                // 提取已存在的手机号
                List<String> existingMobiles = existingRecords.stream()
                        .map(SmsReportInfo::getMobile)
                        .collect(Collectors.toList());

                // 根据手机号批量更新已存在且status为1的记录状态为0
                if (!existingMobiles.isEmpty()) {
                    SmsReportInfo updateEntity = new SmsReportInfo();
                    updateEntity.setStatus(0);

                    QueryWrapper<SmsReportInfo> updateWrapper = new QueryWrapper<>();
                    updateWrapper.in("mobile", existingMobiles);

                    smsReportInfoMapper.update(updateEntity, updateWrapper);
                    log.info("根据手机号批量更新了 {} 条已存在且status为1的记录状态为0", existingMobiles.size());
                }

                // 过滤掉已存在的手机号，只插入新手机号
                Set<String> existingMobileSet = new HashSet<>(existingMobiles);
                reportInfoList = reportInfoList.stream()
                        .filter(info -> !existingMobileSet.contains(info.getMobile()))
                        .collect(Collectors.toList());
            }

            // 插入新的报告信息
            if (!reportInfoList.isEmpty()) {
                int insertedCount = smsReportInfoMapper.insertBatchSomeColumn(reportInfoList);
                log.info("成功批量保存 {} 条新的短信报告信息到数据库", insertedCount);
            } else {
                log.info("没有新的短信报告信息需要保存");
            }
        } catch (Exception e) {
            log.error("批量保存短信报告信息到数据库时发生异常", e);
        }
    }


}
